package com.natalia.excel.exception;

import com.natalia.excel.response.Result;
import com.natalia.excel.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @Author yang
 **/
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class ExceptionControllerAdvice {
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception exception){
        return new Result(ResultCode.FAILED.getCode(), exception.getMessage(),null);
    }

    /**
     * 单个参数验证
     * @param exception
     * @return Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result validExceptionHandler(ConstraintViolationException exception) {
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        String message = constraintViolations.stream()
                .map(ConstraintViolation::getMessage).collect(Collectors.toList()).get(0);
        return  new Result(ResultCode.FAILED.getCode(),message,null);
    }


    /**
     * 处理RequestBody,Validated的校验异常(@Validated)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        String message = exception.getBindingResult().getAllErrors().stream()
                .map(ObjectError::getDefaultMessage).collect(Collectors.toList()).get(0);
        return new Result(ResultCode.FAILED.getCode(),message,null);
    }

    /**
     * bean参数验证(仅对于表单提交有效@Valid)
     *
     * @param exception
     * @return String
     */
    @ExceptionHandler(BindException.class)
    public Result validExceptionHandler(BindException exception) {
        String message = exception.getAllErrors().stream()
                .map(ObjectError::getDefaultMessage).collect(Collectors.toList()).get(0);
        return new Result(ResultCode.FAILED.getCode(),message,null);
    }


}
